package com.unidt.www.module.bpm.service.task;

import com.unidt.www.module.bpm.controller.admin.task.vo.activity.BpmActivityRespVO;
import com.unidt.www.module.bpm.convert.task.BpmActivityConvert;
import com.unidt.www.module.bpm.dal.dataobject.task.BpmTaskExtDO;
import com.unidt.www.module.bpm.dal.mysql.task.BpmTaskExtMapper;
import com.unidt.www.module.bpm.enums.task.BpmProcessInstanceResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.task.api.TaskInfo;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;


/**
 * BPM 活动实例 Service 实现类
 *
 * @author 华院计算源码
 */
@Service
@Slf4j
@Validated
public class BpmActivityServiceImpl implements BpmActivityService {

    @Resource
    private HistoryService historyService;

    @Resource
    BpmTaskExtMapper taskExtMapper;

    @Override
    public List<BpmActivityRespVO> getActivityListByProcessInstanceId(String processInstanceId) {
        List<HistoricActivityInstance> activityList = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId).list();

        /**
         * 找出已经已回退的节点
         */

        Map<String, BpmTaskExtDO> taskExtMap = taskExtMapper.getByProcessInstanceIdAndResult(processInstanceId, BpmProcessInstanceResultEnum.BACK.getResult());

        /**
         * 把回退back的ext数据库，遍历出来，取到taskId
         */
        for(String taskid:taskExtMap.keySet()){
            /**
             * 通过taskId取到histask表的实体
             */
            TaskInfo task= historyService.createHistoricTaskInstanceQuery().taskId(taskid).singleResult();
            /**
             * 取得实体的task'key ；比如Activity_1v1zklo
             */
            String taskKey=task.getTaskDefinitionKey();
            /**
             * 过滤掉从回退过来的  task'key ；比如Activity_1v1zklo，因为有很多一模一样的
             */
            activityList = activityList.stream().filter(e -> !e.getActivityId().contains(taskKey)).collect(Collectors.toList());


            BpmTaskExtDO taskExt = taskExtMapper.selectByTaskId(task.getId());

            /**
             * 回退过来的 状态是5的，刷新成取消CANCEL
             */
            if(taskExt.getResult()==5) {
                // 更新任务
                taskExtMapper.updateById(new BpmTaskExtDO().setId(taskExt.getId()).setResult(BpmProcessInstanceResultEnum.CANCEL.getResult()));
            }
            }

        /**
         * 过滤网关的,不显示 todo 重要
         *
         */
        activityList = activityList.stream().filter(e -> !e.getActivityId().contains("Gateway")).collect(Collectors.toList());

        /**
         * 根据时间倒排
         *
         */
        List<BpmActivityRespVO> list = BpmActivityConvert.INSTANCE.convertList(activityList);
        /**
         * 去掉已经回退的节点 不去显示他
         */
        list = list.stream().filter(e -> !taskExtMap.containsKey(e.getTaskId())).collect(Collectors.toList());



        list = list.stream().sorted(Comparator.comparing(BpmActivityRespVO::getStartTime).reversed()).collect(Collectors.toList());

        Map<String, BpmActivityRespVO> map = new HashMap<>();

        /**
         * 根据key去重处理 取出每个节点（key）
         * 时间最大的一调数据
         */
        list.forEach(b -> {
            String key = b.getKey();

            BpmActivityRespVO activity = map.get(key);
            if (Objects.isNull(activity)) {
                map.put(key, b);
            } else {
                activity.setCount(activity.getCount() + 1);
            }

        });


        List<BpmActivityRespVO> actList = new CopyOnWriteArrayList<>(map.values());


        return actList;
    }

    @Override
    public List<HistoricActivityInstance> getHistoricActivityListByExecutionId(String executionId) {
        return historyService.createHistoricActivityInstanceQuery().executionId(executionId).list();
    }

}
